package com.mlx.mylogin.inter;

import com.mlx.mylogin.base.HttpSnapshot;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 收集基本的请求信息存入Http快照（主要信息是HttpServletRequest与HttpServletResponse对象）
 * 请求进入servlet前保存Http快照，请求退出servlet后移除Http快照；
 * 提供一个进入servlet前利用Http快照的方法：beforeIntoServletUsingHttpSnapshot
 */
public abstract class AbstractHttpSnapshotFilter implements Filter{

    // Http快照容器
    private final ThreadLocal<HttpSnapshot> httpSnapshotContainer = new InheritableThreadLocal<>();

    /**
     * 获取http快照
     * @return http快照
     */
    public HttpSnapshot getHttpSnapshot() {
        return httpSnapshotContainer.get();
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }


    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpSnapshot httpSnapshot = new HttpSnapshot();

        httpSnapshot.setRequest(request);

        httpSnapshot.setResponse(response);

        httpSnapshot.setServletPath(request.getServletPath());

        httpSnapshot.setSession(request.getSession());

        httpSnapshotContainer.set(httpSnapshot);

        try {

            supplementUserData(httpSnapshot);

            filterChain.doFilter(request, response);
        }finally {

            // 移除Http快照
            httpSnapshotContainer.remove();
        }
    }

    protected abstract void supplementUserData(HttpSnapshot httpSnapshot);


}
